package com.qf.spring005.service.impl;

import com.qf.spring005.dao.UserDao;
import com.qf.spring005.entity.User;
import com.qf.spring005.service.UserService;

import java.util.List;

public class UserServiceImpl implements UserService {
    // 依赖Dao层对象
    private UserDao userDao;

    public UserDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public List<User> getAll() {
        return userDao.getAllUsers();
    }

    @Override
    public void transfer(Integer fromId, Integer toId, Integer amount) {
        //1 查询 fromId 对应的账户余额
        User fromuser =  userDao.getUserById(fromId);
        //查看还有多少钱 fromuser.getAmount()
        final Integer fromAmount = fromuser.getAmount();
        //2 计算更新后的金额，进行更新  已有的钱减去要转账的钱
        final int updateFromAmount = fromAmount - amount;

        // 更新用户账户金额
        userDao.updateUserAmount(fromId,updateFromAmount);
         //除0异常
        //int a = 1/0;

        //3. 查询toId对应的账户余额
        User toUser =  userDao.getUserById(toId);

        //查看另一个用户有多少钱toUser.getAmount()
        final Integer toAmount = toUser.getAmount();
        //4. 计算toId对应的账户金额
        final int toUpdateAmount = toAmount + amount;
        //更新另用户账户金额
        userDao.updateUserAmount(toId,toUpdateAmount);
    }
}
